package com.sysd.filter;

import cn.hutool.core.util.StrUtil;
import com.sysd.context.UserContext;
import com.sysd.entity.LoginUser;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @description:
 * @author: bsh
 * @date: 2025/5/30 11:48
 */
public class UserTransmitFilter implements Filter {
    /**
     * 去设置用户的信息到用户上下文里面，这样就可以通过用户上下文快速的获取一些用户的信息
     *
     * @param servletRequest  request
     * @param servletResponse response
     * @param filterChain     过滤
     * @throws IOException      异常
     * @throws ServletException 服务异常
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String token = httpServletRequest.getHeader("token");
        if (StrUtil.isNotBlank(token)) {
            LoginUser loginUser = new LoginUser();
            loginUser.setToken(token);
            UserContext.setUser(loginUser);
        }
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            UserContext.clear();
        }
    }


}
